﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mani.Common.Security;
using RastinArgham.CRM.Business;
using Mani.Common;
using System.Configuration;

namespace RastinArgham.CRM.Web
{
    public partial class personal_contact : System.Web.UI.Page
    {
        public ISecurityManager securityManager { get; set; }
        public CRMRepository crmRepository { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (securityManager == null)
            {
                securityManager = new SecurityManager();
                securityManager.authProvider = new WebAuthorizationProvider();
            }

            if (crmRepository == null)
                crmRepository = new CRMRepository();


            if (!securityManager.IsActionPermitted("add_contact") && !securityManager.IsActionPermitted("view_contact"))
                Response.Redirect("~/access_denied.aspx");

            if (!securityManager.IsActionPermitted("add_contact"))
                btnSave.Visible = false;

            if (!Page.IsPostBack)
            {
                LoadCities();
                LoadUsers();

                if (!String.IsNullOrEmpty(Request.QueryString["id"]))
                    LoadContact();
            }
        }

        private void LoadUsers()
        {
            ddlUsers.ClearSelection();
            ddlUsers.DataSource = securityManager.GetUsers();
            ddlUsers.DataBind();

            ddlUsers.ClearSelection();
            ddlUsers.Items.FindByValue(securityManager.authProvider.GetCurrentUser().UserId.ToString()).Selected = true;

            if (securityManager.IsActionPermitted("change_contact_am"))
                ddlUsers.Enabled = true;
            else
                ddlUsers.Enabled = false;
        }

        private void LoadCities()
        {
            ddlCity.DataSource = crmRepository.GetCitiesByUser(securityManager.authProvider.GetCurrentUser().UserId);
            ddlCity.DataBind();
        }

        private void LoadContact()
        {
            int id = -1;
            if (String.IsNullOrEmpty(Request.QueryString["id"]) || !Int32.TryParse(Request.QueryString["id"], out id))
                return;

            Contact c = crmRepository.GetContactById(id);

            Guid currentUserId = securityManager.authProvider.GetCurrentUser().UserId;
            List<Guid> myAccountManagers = crmRepository.FindMyAccountManagers(currentUserId);

            if (!securityManager.IsActionPermitted("all_contacts") && c.AccountOwner != currentUserId && c.AccountManagerId != currentUserId & !myAccountManagers.Contains(c.AccountManagerId))
                Response.Redirect("~/access_denied.aspx");


            PersonalContact pc = c.PersonalContacts.FirstOrDefault();

            txtFatherName.Text = pc.FatherName;
            txtFirstName.Text = pc.FirstName;
            txtLastName.Text = pc.LastName;
            txtFullContactTitle.Text = c.FullContactTitle;
            txtIdentityNumber.Text = pc.IdentityNumber;
            txtBirthday.Text = pc.Birthday.ToJalali();
            txtNationalCode.Text = pc.NationalCode;
            ddlCity.ClearSelection();
            ddlCity.Items.FindByValue(c.CityId.ToString()).Selected = true;
            txtAddress.Text = c.Address;
            txtZipCode.Text = c.ZipCode;
            txtTel.Text = c.Phone;
            txtMobile.Text = c.MobilePhone;
            txtFax.Text = c.Fax;
            txtEmailAddress.Text = c.Email;
            txtWebsite.Text = c.Website;
            ddlUsers.ClearSelection();
            ddlUsers.Items.FindByValue(c.AccountManagerId.ToString()).Selected = true;

            if (pc.Birthday.HasValue)
                txtBirthday.Text = pc.Birthday.ToJalali();

            txtIdentityIssuePlace.Text = pc.IdentityIssuePlace;
            txtJob.Text = pc.Job;
            txtEducationalMajor.Text = pc.EducationalMajor;
            txtAcademicDegree.Text = pc.AcademicDegree;

            if (!String.IsNullOrEmpty(c.MobinReference))
                txtMobinReference.Text = c.MobinReference;

            if (!String.IsNullOrEmpty(c.Marketer))
                txtMarketer.Text = c.Marketer;

            if (securityManager.IsActionPermitted("change_contact_am"))
                ddlUsers.Enabled = true;
            else
                ddlUsers.Enabled = false;

            ddlCity.Enabled = false;

            if (pc.IdentityPhoto != null)
            {
                imgIDPhoto.Src = "~/GetImage.ashx?ContactId=" + c.ContactId.ToString() + "&Type=PersonalContact_ID&w=50&h=50";
                imgIDPhoto.Visible = true;
                aIDPhoto.Attributes.Add("href", "~/show_image.aspx?ContactId=" + c.ContactId.ToString() + "&Type=PersonalContact_ID");
                aIDPhoto.Visible = true;
            }
            if (pc.ServicePhoto != null)
            {
                imgServiceCertificate.Src = "~/GetImage.ashx?ContactId=" + c.ContactId.ToString() + "&Type=ServicePhoto_CertificatePhoto&w=50&h=50";
                imgServiceCertificate.Visible = true;
                aServiceCertificate.Attributes.Add("href", "~/show_image.aspx?ContactId=" + c.ContactId.ToString() + "&Type=PersonalContact_ServicePhoto");
                aServiceCertificate.Visible = true;
            }

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!securityManager.IsActionPermitted("add_contact"))
                Response.Redirect("~/access_denied.aspx");

            if (String.IsNullOrEmpty(Request.QueryString["id"]))
                New();
            else
                Update();
        }

        private void Update()
        {
            int id = -1;
            if (String.IsNullOrEmpty(Request.QueryString["id"]) || !Int32.TryParse(Request.QueryString["id"], out id))
                return;

            Contact c = crmRepository.GetContactById(id);
            c.Address = txtAddress.Text;
            c.ContactTitle = txtFirstName.Text + " " + txtLastName.Text;
            c.FullContactTitle = txtFullContactTitle.Text;
            c.MobilePhone = txtMobile.Text;
            c.OperatorId = securityManager.authProvider.GetCurrentUser().UserId;
            c.Phone = txtTel.Text;
            c.Email = txtEmailAddress.Text;
            c.Website = txtWebsite.Text;
            c.Fax = txtFax.Text;
            c.ZipCode = txtZipCode.Text;
            c.LastUpdate = DateTime.Now;
            c.AccountManagerId = new Guid(ddlUsers.SelectedValue);

            if (!String.IsNullOrEmpty(txtMobinReference.Text))
                c.MobinReference = txtMobinReference.Text;
            else
                c.MobinReference = String.Empty;

            if (String.IsNullOrEmpty(txtMarketer.Text))
                c.Marketer = String.Empty;
            else
                c.Marketer = txtMarketer.Text;

            PersonalContact pc = c.PersonalContacts.FirstOrDefault();
            pc.FatherName = txtFatherName.Text;
            pc.FirstName = txtFirstName.Text;
            pc.LastName = txtLastName.Text;
            pc.IdentityNumber = txtIdentityNumber.Text;

            if (String.IsNullOrEmpty(txtBirthday.Text))
                pc.Birthday = null;
            else
                pc.Birthday = txtBirthday.Text.ToDateTime();

            pc.IdentityIssuePlace = txtIdentityIssuePlace.Text;
            pc.Job = txtJob.Text;
            pc.EducationalMajor = txtEducationalMajor.Text;
            pc.AcademicDegree = txtAcademicDegree.Text;

            pc.LastUpdate = DateTime.Now;
            pc.NationalCode = txtNationalCode.Text;
            pc.OperatorId = securityManager.authProvider.GetCurrentUser().UserId;

            string message = String.Empty;
            long MinSize = Convert.ToInt64(ConfigurationManager.AppSettings["minImageSize"]);
            long MaxSize = Convert.ToInt64(ConfigurationManager.AppSettings["maxImageSize"]);

            Byte[] IdPhotoBytes = UIHelper.CheckAndGetPostedImage(fuIDPhoto, out message, MinSize, MaxSize);
            if (!String.IsNullOrEmpty(message))
            {
                UIHelper.ClientAlert(this, message);
                return;
            }
            else if ( IdPhotoBytes != null )
            {
                pc.IdentityPhoto = IdPhotoBytes;
            }

            Byte[] ServicePhotoBytes = UIHelper.CheckAndGetPostedImage(fuServiceCertificatePhoto, out message, MinSize, MaxSize);
            if (!String.IsNullOrEmpty(message))
            {
                UIHelper.ClientAlert(this, message);
                return;
            }
            else if (ServicePhotoBytes != null)
            {
                pc.ServicePhoto = ServicePhotoBytes;
            }


            // Checking Dates
            // T-SQL DateTime Valid Range January 1, 1753, through December 31, 9999
            if (!pc.Birthday.HasValue || !DateTimeHelpers.CheckSqlDate(pc.Birthday.Value))
            {
                UIHelper.ClientAlert(this, "تاریخ تولد صحیح نمی باشد لطفا این تاریخ را اصلاح فرمایید");
                return;
            }

            crmRepository.Save();

            UIHelper.ClientAlert(this, "تغییرات با موفقیت ذخیره شد");
            UIHelper.ClientRedirect(this, "dashboard.aspx");
        }

        private void New()
        {
            Contact c = new Contact();
            c.AccountManagerId = new Guid(ddlUsers.SelectedValue);

            if (securityManager.IsUserinRole(securityManager.authProvider.GetCurrentUser().UserName, "mobin"))
            {
                DefaultAccountManager d = crmRepository.GetDefaultAccountManagerForCity(Convert.ToInt32(ddlCity.SelectedValue));
                if (d != null)
                    c.AccountManagerId = d.UserId;
            }

            c.Address = txtAddress.Text;
            c.City = crmRepository.GetCityByid(Convert.ToInt32(ddlCity.SelectedValue));
            c.ContactTitle = txtFirstName.Text + " " + txtLastName.Text;
            c.FullContactTitle = txtFullContactTitle.Text;
            c.ContactType = crmRepository.GetContactTypeById((int)ContactTypes.Personal);
            c.MobilePhone = txtMobile.Text;
            c.OperatorId = securityManager.authProvider.GetCurrentUser().UserId;
            c.Phone = txtTel.Text;
            c.Email = txtEmailAddress.Text;
            c.Website = txtWebsite.Text;
            c.Fax = txtFax.Text;
            c.ZipCode = txtZipCode.Text;
            c.LeadSourceId = 2;
            
            if (securityManager.IsActionPermitted("account_owner"))
                c.AccountOwner = securityManager.authProvider.GetCurrentUser().UserId;
            else
                c.AccountOwner = null;

            if (String.IsNullOrEmpty(txtMobinReference.Text))
                c.MobinReference = String.Empty;
            else
                c.MobinReference = txtMobinReference.Text;

            if (String.IsNullOrEmpty(txtMarketer.Text))
                c.Marketer = String.Empty;
            else
                c.Marketer = txtMarketer.Text;

            PersonalContact pc = new PersonalContact();
            pc.FatherName = txtFatherName.Text;
            pc.FirstName = txtFirstName.Text;
            pc.IdentityNumber = txtIdentityNumber.Text;
            pc.LastName = txtLastName.Text;

            if (String.IsNullOrEmpty(txtBirthday.Text))
                pc.Birthday = null;
            else
                pc.Birthday = txtBirthday.Text.ToDateTime();

            pc.IdentityIssuePlace = txtIdentityIssuePlace.Text;
            pc.Job = txtJob.Text;
            pc.EducationalMajor = txtEducationalMajor.Text;
            pc.AcademicDegree = txtAcademicDegree.Text;

            pc.NationalCode = txtNationalCode.Text;
            pc.OperatorId = securityManager.authProvider.GetCurrentUser().UserId;

            string message = String.Empty;
            long MinSize = Convert.ToInt64(ConfigurationManager.AppSettings["minImageSize"]);
            long MaxSize = Convert.ToInt64(ConfigurationManager.AppSettings["maxImageSize"]);

            Byte[] IdPhotoBytes = UIHelper.CheckAndGetPostedImage(fuIDPhoto, out message, MinSize, MaxSize);
            if (IdPhotoBytes == null && !String.IsNullOrEmpty(message))
            {
                UIHelper.ClientAlert(this, message);
                return;
            }
            else
            {
                pc.IdentityPhoto = IdPhotoBytes;
            }

            Byte[] ServicePhotoBytes = UIHelper.CheckAndGetPostedImage(fuServiceCertificatePhoto, out message, MinSize, MaxSize);
            if (!String.IsNullOrEmpty(message))
            {
                UIHelper.ClientAlert(this, message);
                return;
            }
            else if (ServicePhotoBytes != null)
            {
                pc.ServicePhoto = ServicePhotoBytes;
            }

            // Checking Dates
            // T-SQL DateTime Valid Range January 1, 1753, through December 31, 9999
            if ( !pc.Birthday.HasValue || !DateTimeHelpers.CheckSqlDate(pc.Birthday.Value))
            {
                UIHelper.ClientAlert(this, "تاریخ تولد صحیح نمی باشد لطفا این تاریخ را اصلاح فرمایید");
                return;
            }

            crmRepository.AddPersonalContact(c, pc);

            UIHelper.ClientAlert(this, "تغییرات با موفقیت ذخیره شد");
            UIHelper.ClientRedirect(this, "order_product.aspx?id=" + c.ContactId.ToString());
        }

    }
}